package LeetCode._01算法入门.day02双指针;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author 挚爱之夕
 * @date 2022-02-21 - 02 - 21 - 17:32
 * @Description 给你一个数组，将数组中的元素向右轮转 k 个位置，其中 k 是非负数
 * @Version 1.0
 */
public class _189轮转数组 {
    static int[] nums = {1,2,3,4,5,6,7};
    static int k = 8;
    @Test
    public void solve(){
        rotate(nums, k);
        Arrays.stream(nums).forEach(System.out::print);
    }
    /*by me*/
    public void rotate(int[] nums, int k) {
        int length = nums.length;
        if(k == length){
            return;
        }
        if(k > length){
            k = k% length;
        }
        int[] res = new int[length];
        int pos = 0;

        //开头数的下标
        int index = length - k;
        for(int i = index; i < length ; i++){
            res[pos++] = nums[i];
        }

        for(int i = 0; i < index; i++){
            res[pos++] = nums[i];
        }

        System.arraycopy(res, 0, nums, 0, length);

    }

    /*官方思路*/
    @Test
    public void solve1(){
        rotate1(nums, k);
        Arrays.stream(nums).forEach(System.out::print);
    }
    //辅助空间
    public void rotate1(int[] nums, int k) {
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; ++i) {
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }

    @Test
    public void solve2(){
        rotate2(nums, k);
        Arrays.stream(nums).forEach(System.out::print);
    }
    //3次翻转
    public void rotate2(int[] nums, int k){
        int length = nums.length;
        k %= length;
        //轮转后位于数组首位的数的下标
        int index = length - k;
        //左边
        reverse(nums, 0, index - 1);
        //右边
        reverse(nums, index, length - 1);
        //整体翻转一次
        reverse(nums, 0, length - 1);
    }
    public void reverse(int[] nums, int left, int right){
        while(left < right){
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }

}
